﻿using System;
using System.Net;
using System.Windows.Navigation;
using INdTFramework.Extensions;
using INdTFramework.Http.OAuth;
using INdTFramework.Model;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace OAuthLoginSample.Views
{
    public partial class FacebookWebLoginView : PhoneApplicationPage
    {
        private FacebookAuth fbc;
        public FacebookData FacebookUserData { get; set; }
        public String Url { get; set; }

        public FacebookWebLoginView()
        {
            InitializeComponent();

            fbc = new FacebookAuth("234582059908941", "f087b3a24159f791f74a354e0c020042", "publish_stream,email");
            WebView.Source = new Uri (fbc.GetLoginUrl(), UriKind.RelativeOrAbsolute);
        }

        private void WebView_Navigated(object sender, NavigationEventArgs e)
        {
            String code = e.Uri.GetParamenter("code");
            WebClient webClient = new WebClient();

            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ProcessTokenResponse);
            webClient.DownloadStringAsync(new Uri(fbc.GetAccessTokenRequestUrl(code)));
        }

        protected void ProcessTokenResponse(object sender, DownloadStringCompletedEventArgs e)
        {
            fbc.AccessToken = e.Result.GetParamenter("access_token");

            WebClient webClient = new WebClient();

            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ProcessUserIdResponse);
            webClient.DownloadStringAsync(new Uri(fbc.GetIdUser(fbc.AccessToken)));
        }

        protected void ProcessUserIdResponse(object sender, DownloadStringCompletedEventArgs e)
        {
            FacebookUserData = JsonConvert.DeserializeObject<FacebookData>(e.Result);
            NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));
        }
    }
}